const liveroom = require('../../utils/liveroom.js');
const webimhandler = require('../../utils/webim_handler');
import { getUserInfo } from '../../../common/utils/ws/wsxcx-opendata-sdk';
const device = wx.getSystemInfoSync();

const app = getApp();
let heartbeatInterval = null; 
Page({

  data: {
    // frontCamera: true,
    cameraContext: {},
    pushUrl: '',
    mode: 'SD',
    muted: false,
    enableCamera: true,
    orientation: 'vertical',
    beauty: 6.3,
    whiteness: 3.0,
    backgroundMute: false,
    debug: false,
    headerHeight: app.globalData.headerHeight,
    statusBarHeight: app.globalData.statusBarHeight,
    id: '',
    roomid: '',
    inputMsg: '',
    showComment: false,
    comment: [],
    audienceCount: 0,
    roomTitle: '',
    tip: '',
    tipAnimation: {},
  },
  tips: [],
  tipInterval: null,
  errorCode: {
    '-1301': '打开摄像头失败',
    '-1302': '打开麦克风失败',
    '-1307': '推流连接断开',
    '-1305': '不支持的视频分辨率',
    '-1306': '不支持的音频采样率',
  },
  onSwitchCameraClick: function () {
    // this.data.frontCamera = !this.data.frontCamera;
    // this.setData({
    //   frontCamera: this.data.frontCamera,
    // });
    this.data.cameraContext.switchCamera();
  },
  onBeautyClick: function () {
    if (this.data.beauty != 0) {
      this.data.beauty = 0;
      this.data.whiteness = 0;
    } else {
      this.data.beauty = 6.3;
      this.data.whiteness = 3.0;
    }

    this.setData({
      beauty: this.data.beauty,
      whiteness: this.data.whiteness,
    });
  },
  checkDebug() {
    app.util.request({
      url: 'entry/wxapp/index',
      data: {
        op: 'checkSwitch',
      },
      module: 'cm_lvb',
      success: res => {
        if (res.data && res.data.errno == 0) {
          const data = res.data.data;
          if (data) {
            this.setData({ debug: data.is_debug == 1 });
          }
        }
      },
    });
  },
  onLogClick: function () {
    this.setData({
      debug: !this.data.debug,
    });
  },
  onMuteClick: function () {
    this.setData({
      muted: !this.data.muted,
    });
  },
  onPushEvent: function (e) {
    const errorMsg = this.errorCode[e.detail.code];
    if (errorMsg) {
      wx.showModal({
        title: '系统提示',
        content: errorMsg,
        showCancel: false,
        success: () => {
          if (e.detail.code < 0) {
          wx.navigateBack();
          }
        },
      });
    }
  },
  stop: function () {
    this.setData({
      playing: false,
      pushUrl: '',
      mode: 'SD',
      muted: false,
      enableCamera: true,
      orientation: 'vertical',
      beauty: 6.3,
      whiteness: 3.0,
      backgroundMute: false,
      debug: false,
    });
    this.data.cameraContext.stop({
      success: res => {
        // app.util.request({
        //   url: 'entry/wxapp/index',
        //   data: {
        //     op: 'quitRoom',
        //   },
        //   module: 'cm_lvb',
        //   success: res => {

        //   },
        // });
      },
    });
  },
  createContext: function () {
    let self = this;
    let context = wx.createCanvasContext('caster-comment', self);
    self.ctx = context;
    this.setData({
      cameraContext: wx.createLivePusherContext('camera-push'),
    }, () => {
      self.data.cameraContext.start({
        success:res=>{
          heartbeatInterval = setInterval(() => {
            this.heartbeat();
            this.getAudienceCount();
          }, 5000);
        },
      });
    });
  },
  getAudienceCount() {
    app.util.request({
      url: 'entry/wxapp/index',
      data: {
        op: 'getRoomLists',
      },
      module: 'cm_lvb',
      success: res => {
        const list = res.data.data && res.data.data.lists || [];
        const room = list.find(v => v.roomid == this.options.roomid);
        if (room) {
          this.setData({ audienceCount: room.total });
        }
      },
    });
  },
  isChatSupport() {
    return new Promise((resolve, reject) => {
      app.util.request({
        url: 'entry/wxapp/index',
        data: {
          op: 'is_chat',
        },
        module: 'cm_lvb',
        success: res => {
          console.log('================supportChat',res);
          resolve(res.data && res.data.data && res.data.data.is_chat == 1);
        },
        fail: () => {
          resolve(false);
        },
      });
    });
  },
  onLoad: function (options) {
    console.log('onLoad');
    console.log('============options.pushUrl',decodeURIComponent(options.pushUrl));
    this.setData({
      mode: options.mode,
      orientation: options.orientation,
      enableCamera: Number(options.enableCamera) === 1 ? true : false,
      pushUrl: decodeURIComponent(options.pushUrl),
      id: options.id,
      anchor: decodeURIComponent(options.anchor),
      roomTitle: decodeURIComponent(options.title),
      anchorAvatar: decodeURIComponent(options.anchorAvatar),
      groupID: decodeURIComponent(options.groupID),
      playdomain: decodeURIComponent(options.playdomain),
      playdomainHigh: decodeURIComponent(options.playdomainHigh),
      roomid: options.roomid,
      roomBackground: decodeURIComponent(options.roomBackground),
    });
 
    this.isChatSupport().then(supportChat => {
      this.setData({ supportChat });
      if (supportChat) {
    this.setupLiveRoomListener();
      }
    });
    this.checkDebug();
  },
  onReady: function () {
    console.log('onLoad onReady');
    this.createContext();
    wx.setKeepScreenOn({
      keepScreenOn: true,
    });
    this.animation = wx.createAnimation({
      duration: 500,
      timingFunction: 'ease',
    });
  },
  onShow: function () {
    console.log('onLoad onShow');
    wx.setKeepScreenOn({
      keepScreenOn: true,
    });
  },
  onUnload: function () {
    console.log('onLoad onUnload');
    this.stop();
    this.quitRoom();
    clearInterval(heartbeatInterval);
    wx.setKeepScreenOn({
      keepScreenOn: false,
    });
    if (this.tipInterval) {
      clearInterval(this.tipInterval);
    }
  },
  onBack: function () {
    wx.navigateBack({
      delta: 1,
    });
  },
  quitRoom() {
    let { id } = this.data;
    if (this.data.supportChat) {
    webimhandler.destroyGroup();
    }
    app.util.request({
      url: 'entry/wxapp/index',
      data: {
        op: 'quitRoom',
        id,
      },
      module: 'cm_lvb',
      success: res => {

      },
    });
  },
  heartbeat(){
    let { roomid } = this.options;
    app.util.request({
      url: 'entry/wxapp/index',
      data: {
        op: 'setRoomHeart',
        roomid,
      },
      module: 'cm_lvb',
      success: res => {
        console.log('=====================pusher heartbeat success', res);
      },
    });
  },
  showComment() {
    this.setData({
      inputMsg: '',
      showComment: true,
    });
  },
  hideComment() {
    this.setData({
      inputMsg: '',
      showComment: false,
    });
  },
  bindInputMsg(e) {
    this.setData({
      inputMsg: e.detail.value,
    });
  },
  sendComment() {
    if (this.data.inputMsg) {
      this.sendTextMsg(this.data.inputMsg);
    }
    this.setData({
      inputMsg: '',
      showComment: false,
    });
  },
  setupLiveRoomListener() {
    liveroom.setListener({
      onRoomClose: this.onRoomClose,
      onRecvRoomTextMsg: this.onRecvRoomTextMsg,
      onRecvGroupTip: this.onRecvGroupTip,
    });
  },
  onRoomClose(e) {
    console.log('onRoomClose: e=', e);
  },
  onRecvRoomTextMsg(ret) {
    console.log('onRecvRoomTextMsg called, ret: ', ret);
    this.data.comment.unshift({
      content: ret.message,
      name: ret.userName,
      time: ret.time,
    });
    this.setData({
      comment: this.data.comment.slice(0, 8),
    }, () => {
      this.updateComment();
    });
  },
  onRecvGroupTip(ret) {
    console.log('onRecvGroupTip called, ret: ', ret);
    if (ret.type === 'join') {
      this.tips.push(ret.message);
      this.showTip();
    } else {
    this.onRecvRoomTextMsg(ret);
    }
  },
  showTip() {
    if (!this.tipInterval) {
      this.showTipAnimation();
      this.tipInterval = setInterval(() => {
        this.showTipAnimation();
      }, 4000);
    }
  },
  showTipAnimation() {
    if (this.tips && this.tips.length > 0) {
      this.animation.left('-750rpx').translateX(device.windowWidth).step();
      this.setData({
        tip: this.tips.pop(),
        tipAnimation: this.animation.export(),
      }, () => {
        setTimeout(() => {
          this.animation.translateX(-device.windowWidth).step();
          this.setData({
            tipAnimation: this.animation.export(),
          });
        }, 2800);
      });
    }
  },
  wrapTextLine(text) {
    let width = 15;
    let textArray = text.split('');
    let lines = [];
    let line = '';
    for (let i = 0; i < textArray.length; i++) {
      let temp = line + textArray[i];
      if (this.ctx.measureText(temp).width + width >= 276 && i > 0) {
        lines.push(line);
        line = textArray[i];
      } else {
        line = temp;
  }
      if (i == textArray.length - 1) {
        lines.push(line);
      }
    }
    return lines;
  },
  updateComment() {
    const comment = this.data.comment;
    this.ctx.font = 'normal bold 14px PingFangSC';
    comment.forEach((element) => {
      this.ctx.setFillStyle('#fff');
      let text = element.name ? `${element.name}: ${element.content}` : element.content;
      let lines = this.wrapTextLine(text);
      let namePrinted = true;
      element.lines = [];
      element.lineCount = lines.length;
      lines.forEach((line, index) => {
        if (index === 0) {
          if (line.indexOf(':') > -1) {
            let o = line.indexOf(':');
            let text = line.slice(0, o + 1);
            element.lines.push({
              text,
              color: '#00ECFE',
              inline: true,
              width: this.ctx.measureText(text).width,
            });
            text = line.slice(o + 1);
            element.lines.push({
              text,
              inline: true,
              width: this.ctx.measureText(text).width,
            });
            namePrinted = true;
          } else {
            element.lines.push({
              text: line,
              color: '#00ECFE',
            });
            namePrinted = false;
          }
        } else {
          if (namePrinted) {
            element.lines.push({
              text: line,
            });
          } else {
            let r = line.indexOf(':');
            if (r > -1) {
              let text = line.slice(0, r + 1);
              element.lines.push({
                text,
                color: '#00ECFE',
                inline: true,
              });
              text = line.slice(r + 1);
              element.lines.push({
                text,
                inline: true,
              });
              namePrinted = true;
            } else {
              element.lines.push({
                text: line,
                color: '#00ECFE',
              });
              namePrinted = false;
            }
          }
        }
      });
    });
    this.setData({
      casterComment: JSON.parse(JSON.stringify(comment)).reverse(),
    });
  },
  sendTextMsg(text) {
    if (text.startsWith('>')) {
      switch (text) {
        case '>debug': {
          this.onLogClick();
          return;
        }
      }
    }
    getUserInfo().then(userInfo => {
    const anchor = this.data.anchor;
      const avatar = userInfo.avatarUrl;
    webimhandler.sendCustomMsg({
      data: '{"cmd":"CustomTextMsg","data":{"nickName":"' + anchor + '","headPic":"' + avatar + '"}}',
      text: text,
    }, function () {
      });
    }).catch(res => {
      app.util.navigateTo('/cm_lvb/pages/auth/auth');
    });
  },
  toLiveList() {  
    const pages = getCurrentPages();
    if (pages && pages.length > 1) {
    wx.navigateBack();
    } else {
      app.util.navigateTo('/cm_lvb/pages/index/index');
    }
  },
  onShareAppMessage() {
    const { 
      roomTitle: title = '',
      playdomain = '',
      playdomainHigh = '',
      id = '',
      roomid = '',
      groupID = '',
      roomBackground: imageUrl = '',
      anchor = '',
      anchorAvatar: avatar = '',
    } = this.data;

    return {
      title,
      path: `/cm_lvb/pages/play/play?playdomain=${playdomain}&playdomainHigh=${playdomainHigh}&id=${id}&roomid=${roomid}&groupID=${groupID}&anchor=${anchor}&avatar=${avatar}&roomBackground=${imageUrl}&roomTitle=${title}`,
      imageUrl,
      success: res => {
        console.log('分享成功', res);
      },
    };
  },
});
